const bodyParser = require('body-parser');
let { list } = require('./mock')
const userList = [{
	username: '13111111111',
	password: '000000',
	nickname: '追梦的人',
	role: 'admin'
}, {
	username: '14111111111',
	password: '000000',
	nickname: '做梦的人',
	role: 'user'
}, {
	username: '15111111111',
	password: '000000',
	nickname: '睡梦的人',
	role: 'user'
}]

module.exports = app => {
	app.use(bodyParser.json())
	// 登录
	app.post('/api/login', (req, res) => {
		// 获取用户-密码
		const { username, password } = req.body;
		// 验证
		const user = userList.find(v => v.username === username && v.password === password)
		if (user) {
			res.send({
				code: 200,
				message: '登录成功， 欢迎' + user.nickname,
				data: {
					role: user.role,
					nickname: user.nickname
				}
			})
		} else {
			res.send({
				code: 403,
				message: '账户密码错误， 请重新登录',
				data: null
			})
		}
	})
	// 列表获取
	app.get('/api/list', (req, res) => {
		const { keyword, min, max } = req.query
		let newList = [...list]
		if (keyword) {
			newList = newList.filter(v => {
				return v.id.includes(keyword) || v.title.includes(keyword) || v.word.includes(keyword) || v.price.toString().includes(keyword)
			})
		}
		if (min >= 0 && max > 0) {
			newList = newList.filter(v => {
				return v.price >= min && v.price <= max
			})
		}
			res.send({
				code: 200,
				data: newList,
				message: "数据获取成功！！"
			})

	})
	// 列表删除
	app.delete('/api/list', (req, res) => {
		// 1. 获取删除的id
		const { id } = req.query;
		// 2. 过滤数据
		list = list.filter(v => v.id !== id);
		res.send({
			code: 200,
			message: '数据删除成功'
		})
	})

	// 列表数据修改
	app.post('/api/list/update', (req, res) => {
		// 等待更新的数据
		const { id } = req.body;
		// 老数据
		const item = list.find(v => v.id === id);
		// 对象合并
		Object.assign(item, req.body)
		res.send({
			code: 200,
			message: '修改成功'
		})
	})
}


// 123            1  2  3  12 23 123 